/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.ItemManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import resource.Item;
import resource.Macro;
import utilities.Codecs;
import utilities.DBConnector;
import utilities.Helper;
import utilities.Validation;
import utilities.Prompt;

/**
 *
 * @author fangchengjia
 */
public class ItemManagerBase extends javax.swing.JFrame{
    private final DBConnector dbSession;
    private javax.swing.JTable itemTable;
    
    public final String TABLE_MODEL[] = new String[] {
        Macro.ITEM_CALL_NUMBER_L,
        Macro.ITEM_TYPE_L,
        Macro.ITEM_NAME_L,
        Macro.ITEM_AUTHOR_L,
        Macro.ITEM_PUBLISH_YEAR_L,
        Macro.ITEM_PUBLISHER_L,
        Macro.ITEM_CATEGORY_L,
        Macro.ITEM_ISBN_L,
        Macro.ITEM_REGISTER_DATE_L,
        Macro.ITEM_PRICE_L,
        Macro.ITEM_STATUS_L,
        Macro.ITEM_OWNER_L,
        Macro.ITEM_RETURN_DATE_L,
        Macro.ITEM_NOTES_L,
        Macro.ITEM_ID_L
    };
    
    /**
     * Creates new form CategoryManager
     * @param dbSession
     */
    public ItemManagerBase(DBConnector dbSession) {
        this.dbSession = dbSession;
    }
    
    public DBConnector getDBSession(){
        return dbSession;
    }
    
    public javax.swing.JTable getTargetTable(){
        return itemTable;
    }
    
    public void setTargetTable(javax.swing.JTable itemTable){
        this.itemTable = itemTable;
    }
    
    public void refresh(){
        Helper.refresh(dbSession, Macro.DB_ITEM, TABLE_MODEL, itemTable);
    }
    
    public void searchAvailableItems(){
        Helper.searchBy(dbSession, Macro.DB_ITEM, TABLE_MODEL, itemTable, 
                Macro.ITEM_STATUS_L, Macro.ITEM_STATUS_ON_SHELF);
    }
    
    public void searchLoanedItems(){
        Helper.searchBy(dbSession, Macro.DB_ITEM, TABLE_MODEL, itemTable, 
                Macro.ITEM_STATUS_L, Macro.ITEM_STATUS_ON_LOAN);
    }
    
    public void searchByCallNumber(String value){
        Helper.searchBy(dbSession, Macro.DB_ITEM, TABLE_MODEL, itemTable, 
                Macro.ITEM_CALL_NUMBER_L, value);
    }
    
    public void searchByISBN(String value){
        Helper.searchBy(dbSession, Macro.DB_ITEM, TABLE_MODEL, itemTable, 
                Macro.ITEM_ISBN_L, value);
    }
    
    public boolean inputCheck(Item item){
        if (Validation.empty("Author", item.getAuthor())){
            return false;
        }
        if (item.getAuthor().split(" ").length < 2){
            Prompt.warning(Macro.WARNING_FORMAT, "Author", "Firtname Lastname");
            return false;
        }
        if (item.getStatus().equals(Macro.ITEM_STATUS_ON_LOAN)){
            if (item.getOwner().equals(Macro.ITEM_OWNER_NONE)){
                Prompt.warning(Macro.WARNING_INVALID, "Owner");
                return false;
            }
            if (!Validation.validDate("Return Date", item.getReturnDate(),
                    Macro.REGEX_DATE, "yyyy-mm-dd")){
                return false;
            }
        }
        if (!item.getOwner().equals(Macro.ITEM_OWNER_NONE)){
            String expiry_date = Helper.searchOwnerAttributeByName(
                    dbSession, Macro.DB_MEMBERSHIP,
                    Codecs.encode(item.getOwner()),
                    Macro.MEMBERSHIP_EXPIRY_DATE_L);
            try {
                Date expire = new SimpleDateFormat("yyyy-MM-dd",
                        Locale.ENGLISH).parse(expiry_date);
                if (new Date().after(expire)){
                    Prompt.warning("Membership has expired");
                    return false;
                }
            } catch (ParseException ex) {
                Logger.getLogger(ItemManagerBase.class.getName()).
                        log(Level.SEVERE, null, ex);
            }
        }
        return !Validation.empty("Name", item.getName()) &&
                Validation.validFormat("Publish Year", item.getPublishYear(),
                        Macro.REGEX_YEAR, "yyyy") &&
                Validation.validDate("Register Date", item.getRegisterDate(),
                        Macro.REGEX_DATE, "yyyy-mm-dd") &&
                Validation.valideRecord(dbSession, Macro.DB_CATEGORY,
                        Macro.ITEM_NAME_L, item.getCategory());
    }
    
    public void updateItem(Item item){
        if (inputCheck(item)){
            String tmp_call_no = callNumGenerator(item.getCategory(), 
                    item.getAuthor(), item.getPublishYear());
            item.setCallNumber(tmp_call_no);
            String values[] = item.getValues();
            if (dbSession.check(Macro.DB_ITEM,
                    String.format("%s='%s'", Macro.ITEM_ID_L, 
                        Codecs.encode(item.getId())))){
                dbSession.update(Macro.DB_ITEM,
                        Helper.encodeValues(TABLE_MODEL, values),
                        String.format("%s='%s'", Macro.ITEM_ID_L, 
                            Codecs.encode(item.getId())));
                dispose();
            }
            else{
                Prompt.warning("The record does not exist.");
            }
        }
    }
    
    public String callNumGenerator(String category, String author,
            String publishYear){
        String split_list[] = author.split(" ");
        String last_name = split_list[split_list.length - 1];
        String first_char = String.valueOf(last_name.charAt(0));
        String second_char = String.valueOf(last_name.charAt(1));
        String third_char = "";
        if (last_name.length() >= 3){
            third_char =  String.valueOf(last_name.charAt(2));
        }
        String final_str = first_char+second_char+third_char;
        String category_num = dbSession.load(Macro.DB_CATEGORY,
                String.format("%s='%s'", Macro.CATEGORY_NAME_L,
                        Codecs.encode(category)), Macro.CATEGORY_CLASS_L);
        return String.format("%s %s %s",
            Codecs.decode(category_num), final_str.toUpperCase(), publishYear);
    }
}
